package com.my.framework.web.mvc.controller;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.my.annotation.Property;
import com.my.exception.Message;
import com.my.toolkit.JsonUtil;
import com.my.utils.ClassUtil;
import com.my.utils.StringUtil;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;


public class BaseController {
	private static Logger baseControllerLog = LoggerFactory.getLogger(BaseController.class);
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	
	@Autowired
	protected JsonUtil jsonUtil;

	// 根据配置的validate字段验证
	public  void prepareAdd(Object obj) {
		List<Field> fields = ClassUtil.getFieldsByAnnotation(obj.getClass(), Property.class);
		for (Field f : fields) {
			Object value = null;
			try {
				f.setAccessible(true);
				value = f.get(obj);
			} catch (Exception ex) {
				throw new RuntimeException("获取字段出错:" + obj.getClass().getSimpleName() + "." + f.getName(), ex);
			}
			validate(f, value);
		}
	}

	private  void validate(Field field, Object value) {
		Property col = field.getAnnotation(Property.class);
		String name = col.value();
		String validate = col.validate();
		if (StringUtil.isEmpty(validate)) {
			return;
		}
		int length = col.length();
		if (length > 0 && (value + "").length() > length) {
			throw new Message(shortName(name) + "的长度不能超过" + length);
		}
		String[] validates = validate.split(",");
		for (String va : validates) {
			if ("notNull".equals(va)) {
				if (StringUtil.isEmpty(value)) {
					throw new Message(shortName(name) + "不能为空");
				}
				continue;
			}
			if ("unique".equals(va)) {
				baseControllerLog.info("唯一约束暂时靠数据库");
				continue;
			}
			throw new RuntimeException(va + "验证未实现");
		}

	}

	@SneakyThrows
	public static <T> void assertNotNull(Object obj, String field) {
		List<Field> fields = ClassUtil.getFieldsByAnnotation(obj.getClass(), Property.class);
		for (Field f : fields) {
			if (f.getName().equalsIgnoreCase(field)) {
				Property prop = f.getAnnotation(Property.class);
				String name = prop.value();
				f.setAccessible(true);
				Object value = f.get(obj);
				if (StringUtil.isEmpty(value)) {
					throw new Message(shortName(name) + "不能为空");
				}
				return;
			}
		}
	}

	private static String shortName(String name) {
		int i = name.indexOf(",");
		if (i != -1) {
			return name.substring(0, i);
		}
		return name;
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(timeFormat, true) {
			public void setAsText(@Nullable String text) throws IllegalArgumentException {
				if (StringUtil.isEmpty(text)) {
					setValue(null);
					return;
				}
				text = text.trim();

				try {
					if (text.indexOf(" ") != -1) {
						setValue(timeFormat.parse(text));
					} else {
						setValue(dateFormat.parse(text));
					}

				} catch (ParseException ex) {
					throw new Message("日期格式不正确:"+text);
				}

			}
		});
	}
}
